<?php

Yii::import('zii.widgets.grid.CGridView');

class CMyGridView extends CGridView
{
	
	private $_group;
	
	public $selectableRows=0;
	
	/**
	 * @var boolean whether to hide the header cells of the grid. When this is true, header cells
	 * will not be rendered, which means the grid cannot be sorted anymore since the sort links are located
	 * in the header. Defaults to false.
	 * @since 1.1.1
	 */
	public $hideGroupHeader=false;
	
	/**
	 * @var string 
	 */
	public $groupName;
	
	/**
	 * Initializes the grid view.
	 * This method will initialize required property values and instantiate {@link columns} objects.
	 */
	public function init()
	{
		parent::init();
	}


	/**
	 * @return boolean whether the table should render a footer.
	 * This is true if any of the {@link columns} has a true {@link CGridColumn::hasFooter} value.
	 */
	public function getHasGroupFooter()
	{
		foreach($this->groupColumns as $column)
			if($column->getHasFooter())
				return true;
		return false;
	}	
	
	public function renderGroupHeader($group)
	{

		if(!$this->hideGroupHeader)
//			if ($this->)
		{
			echo '<tbody class="group_header">';
						
			echo '<tr><td>';
				echo $group;
			echo '</td><td colspan="'. (count($this->columns)-1) .'"></td></tr>';

			echo "</tbody>\n";
		}
	}
	
	public function renderGroupFooter($rows)
	{
		if($this->getHasFooter())
		{
			echo '<tbody class="group_footer">';
			echo "<tr>\n";
			foreach($this->columns as $column)
				$column->renderFooterCell($rows);
			echo "</tr>\n";			
			echo "</tbody>\n";
		}		
	}

	/**
	 * Renders the table body.
	 */
	public function renderTableBody()
	{
		$data=$this->dataProvider->getData();
		$n=count($data);		
		
		if($n>0)
		{
			if (is_string($this->groupName))
			{
				$groups = array();
				for($row=0;$row<$n;++$row)
				{		
					$groupId=CHtml::value($data[$row],$this->groupName);								
					if(!isset($groups[$groupId]))
						$groups[$groupId]=array();
					$groups[$groupId][]=$row;
				}
				foreach($groups as $group=>$rows)
				{
					$this->renderGroupHeader($group);
					echo "<tbody>\n";
					foreach($rows as $row)
						$this->renderTableRow($row);
					echo "</tbody>\n";
					$this->renderGroupFooter($rows);
				}				
			}
			else
			{
				echo "<tbody>\n";
				for($row=0;$row<$n;++$row)
					$this->renderTableRow($row);
				echo "</tbody>\n";
			}
		}
		else
		{
			echo "<tbody>\n";
			echo '<tr><td colspan="'.count($this->columns).'">';
			$this->renderEmptyText();
			echo "</td></tr>\n";
			echo "</tbody>\n";
		}
	}

}
